//
// Created by wznh on 2024/10/16.
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_SIZE 100  // 定义最大节点数
#define MAX_NAME_LEN 50  // 定义最大姓名长度
#define MAX_CLASS_LEN 20  // 定义最大班级长度

// 定义学生信息结构体
typedef struct Student {
    char name[MAX_NAME_LEN];  // 学生姓名
    char class[MAX_CLASS_LEN];  // 学生班级
    float score;  // 学生成绩
    int next;  // 指针域，静态分配时使用数组索引
} StudentNode;

// 定义链表结构体
typedef struct {
    StudentNode students[MAX_SIZE];  // 学生节点数组
    int length;  // 链表当前长度
    int head;   // 头节点索引
} StudentList;

// 初始化学生信息链表
void initStudentList(StudentList *list) {
    list->length = 0;
    list->head = -1;  // 空链表的头节点索引为-1
    for (int i = 0; i < MAX_SIZE - 1; i++) {
        list->students[i].next = i + 1;  // 初始化指针域，形成循环链
    }
    list->students[MAX_SIZE - 1].next = -1;  // 最后一个节点的指针域为-1
}

// 销毁学生信息链表
void destroyStudentList(StudentList *list) {
    list->length = 0;
    list->head = -1;
}

// 在链表中插入学生信息
int insertStudent(StudentList *list, const char *name, const char *classStr, float score, int position) {
    if (list->length == MAX_SIZE) {
        printf("List is full.\n");
        return -1;
    }
    if (position < 0 || position > list->length) {
        printf("Invalid position.\n");
        return -1;
    }
    int newIndex = list->length;
    if (position == list->length) {
        // 插入到链表末尾
        if (list->head == -1) {
            list->head = newIndex;
        } else {
            list->students[list->students[list->length - 1].next].next = newIndex;
        }
    } else {
        // 插入到链表中间
        int prevIndex = (position == 0) ? -1 : findIndex(list, position - 1);
        int nextIndex = list->students[prevIndex].next;
        list->students[prevIndex].next = newIndex;
        list->students[newIndex].next = nextIndex;
    }
    // 设置学生信息
    strncpy(list->students[newIndex].name, name, MAX_NAME_LEN);
    strncpy(list->students[newIndex].class, classStr, MAX_CLASS_LEN);
    list->students[newIndex].score = score;
    list->length++;
    return 0;  // 插入成功
}

// 打印所有学生信息
void printStudentList(StudentList *list) {
    int index = list->head;
    while (index != -1) {
        printf("Name: %s, Class: %s, Score: %.2f\n", list->students[index].name, list->students[index].class, list->students[index].score);
        index = list->students[index].next;
    }
}

// 查找学生信息的索引
int findIndex(StudentList *list, int position) {
    if (position < 0 || position >= list->length) {
        return -1;
    }
    int index = list->head;
    for (int i = 0; i < position; i++) {
        index = list->students[index].next;
    }
    return index;
}

int main() {
    StudentList list;
    initStudentList(&list);

    insertStudent(&list, "Alice", "Class 1", 88.5, 0);
    insertStudent(&list, "Bob", "Class 2", 93.0, 1);
    insertStudent(&list, "Charlie", "Class 3", 77.5, 2);

    printf("Student List:\n");
    printStudentList(&list);

    destroyStudentList(&list);
    return 0;
}